'use client';

import { useState, useEffect, useRef } from 'react';
import Sidebar from '@/components/Sidebar';
import dynamic from 'next/dynamic';

interface HistoryItem {
  url: string;
  title: string;
  timestamp: number;
  isFavorite: boolean;
  description?: string;
}

interface ParseApi {
  name: string;
  url: string;
  available: boolean;
  tag?: string;
}

const PARSE_APIS: ParseApi[] = [
  {
    name: '接口1',
    url: 'https://jx.xmflv.com/?url=',
    available: true,
    tag: '可用'
  },
  {
    name: '接口2',
    url: 'https://jx.parwix.com:4433/player/?url=',
    available: false
  },
  {
    name: '接口3',
    url: 'https://jx.iztyy.com/svip/?url=',
    available: false
  },
  {
    name: '接口4',
    url: 'https://jx.bozrc.com:4433/player/?url=',
    available: false
  },
  {
    name: '接口5',
    url: 'https://jx.4kdv.com/?url=',
    available: false
  }
];

// 动态导入视频播放器组件，避免SSR问题
const ReactVideoPlayer = dynamic(() => import('@/components/ReactVideoPlayer'), { 
  ssr: false,
  loading: () => (
    <div className="pt-[56.25%] w-full bg-gray-800 rounded-lg overflow-hidden relative">
      <div className="absolute inset-0 flex items-center justify-center">
        <div className="flex flex-col items-center">
          <svg className="animate-spin h-8 w-8 text-white mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span className="text-white text-sm">加载播放器中...</span>
        </div>
      </div>
    </div>
  )
});

export default function Home() {
  const [videoUrl, setVideoUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [currentApiIndex, setCurrentApiIndex] = useState(0);
  const [showApiSelector, setShowApiSelector] = useState(false);
  const [darkMode, setDarkMode] = useState(false);
  const [username, setUsername] = useState('用户');
  const [showCustomTitle, setShowCustomTitle] = useState(false);
  const [customTitle, setCustomTitle] = useState('');
  const [showDescription, setShowDescription] = useState(false);
  const [description, setDescription] = useState('');
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [playInNewTab, setPlayInNewTab] = useState(true);
  const [isEmbedPlaying, setIsEmbedPlaying] = useState(false);
  const [currentPlayingUrl, setCurrentPlayingUrl] = useState('');
  const [embedTitle, setEmbedTitle] = useState('');
  const [iframeLoading, setIframeLoading] = useState(true);
  const [iframeError, setIframeError] = useState(false);
  const [loadingTimeout, setLoadingTimeout] = useState(false);
  const iframeTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  const apiSelectorRef = useRef<HTMLDivElement>(null);
  const customTitleRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);

  // 初始化主题
  useEffect(() => {
    // 检查本地存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;

    // 根据保存的设置或系统偏好设置主题
    if (savedTheme === 'light') {
      // 用户明确设置为亮色
      setDarkMode(false);
      document.documentElement.classList.remove('dark');
    } else if (savedTheme === 'dark') {
      // 用户明确设置为暗色
      setDarkMode(true);
      document.documentElement.classList.add('dark');
    } else {
      // 没有保存过主题，根据系统偏好设置
      setDarkMode(systemPrefersDark);
      if (systemPrefersDark) {
        document.documentElement.classList.add('dark');
        localStorage.setItem('theme', 'dark');
      } else {
        document.documentElement.classList.remove('dark');
        localStorage.setItem('theme', 'light');
      }
    }

    // 监听主题变化事件（从其他页面触发的）
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      setDarkMode(newTheme === 'dark');
      if (newTheme === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    };

    window.addEventListener('themeChange', handleThemeChange as EventListener);
    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  // 加载用户设置
  useEffect(() => {
    // 加载是否在新标签页播放视频的设置
    const savedPlayInNewTab = localStorage.getItem('playInNewTab');
    if (savedPlayInNewTab !== null) {
      setPlayInNewTab(savedPlayInNewTab === 'true');
    }
    
    // 监听播放模式变化事件（从其他页面触发的）
    const handlePlayModeChange = (e: CustomEvent) => {
      setPlayInNewTab(e.detail.playInNewTab);
    };

    window.addEventListener('playModeChange', handlePlayModeChange as EventListener);
    
    // 加载用户名
    const savedUsername = localStorage.getItem('username');
    if (savedUsername) {
      setUsername(savedUsername);
    }
    
    return () => {
      window.removeEventListener('playModeChange', handlePlayModeChange as EventListener);
    };
  }, []);

  useEffect(() => {
    const savedHistory = localStorage.getItem('videoHistory');
    if (savedHistory) {
      setHistory(JSON.parse(savedHistory));
    }
  }, []);

  useEffect(() => {
    // 点击外部关闭接口选择器和标题输入框
    function handleClickOutside(event: MouseEvent) {
      if (apiSelectorRef.current && !apiSelectorRef.current.contains(event.target as Node)) {
        setShowApiSelector(false);
      }
      
      if (customTitleRef.current && !customTitleRef.current.contains(event.target as Node)) {
        // 我们不在这里关闭标题输入框，因为我们希望用户通过按钮来控制它
        // setShowCustomTitle(false);
      }
      
      if (descriptionRef.current && !descriptionRef.current.contains(event.target as Node)) {
        // 不在这里关闭描述输入框，由用户通过按钮控制
        // setShowDescription(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const saveHistory = (newHistory: HistoryItem[]) => {
    setHistory(newHistory);
    localStorage.setItem('videoHistory', JSON.stringify(newHistory));
  };

  // 处理URL，移除?后的所有参数
  const cleanUrl = (url: string) => {
    try {
      const urlObj = new URL(url);
      return urlObj.origin + urlObj.pathname;
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      // 如果不是有效URL，直接返回原始值
      return url;
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setIframeError(false);
    setLoadingTimeout(false);

    try {
      try {
        new URL(videoUrl);
      } catch {
        throw new Error('无效的视频链接');
      }

      // 清理URL，移除?后的所有参数
      const cleanedUrl = cleanUrl(videoUrl);
      
      // 确定视频标题
      const defaultTitle = cleanedUrl.split('/').pop() || '未知视频';
      const videoTitle = customTitle.trim() ? customTitle.trim() : defaultTitle;
      
      const newHistoryItem: HistoryItem = {
        url: cleanedUrl,
        title: videoTitle,
        timestamp: Date.now(),
        isFavorite: false,
        description: description.trim() || undefined,
      };
      
      saveHistory([newHistoryItem, ...history]);
      setCustomTitle(''); // 重置自定义标题
      setShowCustomTitle(false); // 隐藏输入框
      setDescription(''); // 重置描述
      setShowDescription(false); // 隐藏描述输入框

      const parseUrl = PARSE_APIS[currentApiIndex].url + encodeURIComponent(cleanedUrl);
      
      // 根据设置决定在新标签页打开还是内嵌播放
      if (playInNewTab) {
        try {
          window.open(parseUrl, '_blank');
        } catch (error) {
          console.error("打开新标签页失败:", error);
          // 尝试备用方法
          const a = document.createElement('a');
          a.href = parseUrl;
          a.target = '_blank';
          a.rel = 'noopener noreferrer';
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
        }
      } else {
        // 内嵌播放
        setIframeLoading(true);
        setCurrentPlayingUrl(parseUrl);
        setEmbedTitle(videoTitle);
        setIsEmbedPlaying(true);
        
        // 设置超时定时器
        if (iframeTimerRef.current) {
          clearTimeout(iframeTimerRef.current);
        }
        
        iframeTimerRef.current = setTimeout(() => {
          setIframeLoading(false);
          setLoadingTimeout(true);
        }, 15000); // 15秒超时
        
        // 滚动到视频播放区域
        setTimeout(() => {
          document.getElementById('video-player-section')?.scrollIntoView({ behavior: 'smooth' });
        }, 100);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '解析失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const selectApi = (index: number) => {
    setCurrentApiIndex(index);
    setShowApiSelector(false);
  };

  // 关闭内嵌播放器
  const closeEmbedPlayer = () => {
    setIsEmbedPlaying(false);
    setCurrentPlayingUrl('');
    setEmbedTitle('');
    setIframeLoading(false);
    setIframeError(false);
    setLoadingTimeout(false);
    
    // 清除定时器
    if (iframeTimerRef.current) {
      clearTimeout(iframeTimerRef.current);
      iframeTimerRef.current = null;
    }
  };

  // 处理iframe加载完成
  const handleIframeLoad = () => {
    setIframeLoading(false);
    setIframeError(false);
    setLoadingTimeout(false);
    
    // 清除定时器
    if (iframeTimerRef.current) {
      clearTimeout(iframeTimerRef.current);
      iframeTimerRef.current = null;
    }
  };
  
  // 处理iframe加载错误
  const handleIframeError = () => {
    setIframeLoading(false);
    setIframeError(true);
    
    // 清除定时器
    if (iframeTimerRef.current) {
      clearTimeout(iframeTimerRef.current);
      iframeTimerRef.current = null;
    }
  };
  
  // 在新标签页打开当前视频
  const openInNewTab = () => {
    if (currentPlayingUrl) {
      console.log("在新标签页打开:", currentPlayingUrl);
      try {
        window.open(currentPlayingUrl, '_blank');
      } catch (error) {
        console.error("打开新标签页失败:", error);
        // 尝试备用方法
        const a = document.createElement('a');
        a.href = currentPlayingUrl;
        a.target = '_blank';
        a.rel = 'noopener noreferrer';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
    }
  };

  

  return (
    <div className="flex h-full">
      {/* 侧边栏 */}
      <Sidebar 
        darkMode={darkMode} 
        username={username} 
        isOpen={sidebarOpen} 
        onToggle={() => setSidebarOpen(!sidebarOpen)} 
      />
      
      {/* 主内容区 */}
      <div className={`flex-1 md:ml-64 bg-white dark:bg-black min-h-screen text-black dark:text-white flex flex-col transition-all duration-300 ${
        sidebarOpen ? 'md:translate-x-0' : 'translate-x-0'
      }`}>
        {/* 顶部导航 */}
        <nav className="border-b border-gray-100 dark:border-gray-800">
          <div className="max-w-5xl mx-auto px-4 py-4 flex items-center">
            {/* 移动端汉堡菜单按钮 */}
            <button
              className="md:hidden mr-4 text-gray-600 dark:text-gray-400"
              onClick={() => setSidebarOpen(!sidebarOpen)}
              aria-label="打开菜单"
            >
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
              </svg>
            </button>
            <h1 className="text-xl font-medium">解析视频</h1>
            <div className="ml-auto text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2">
              当前接口: {PARSE_APIS[currentApiIndex].name}
              {PARSE_APIS[currentApiIndex].tag && (
                <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100">
                  {PARSE_APIS[currentApiIndex].tag}
                </span>
              )}
            </div>
          </div>
        </nav>

        <main className="flex-1 max-w-5xl mx-auto px-4 py-8 w-full">
          {/* 搜索区域 */}
          <section className="mb-12">
            <div>
              <form onSubmit={handleSubmit} className="relative">
                <input
                  type="text"
                  value={videoUrl}
                  onChange={(e) => setVideoUrl(e.target.value)}
                  placeholder="粘贴视频链接"
                  className="w-full py-3 px-4 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-black focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500"
                />
                <div className="mt-2 flex flex-wrap gap-2 justify-end sm:absolute sm:right-1.5 sm:top-1.5 sm:mt-0">
                  <button
                    type="button"
                    onClick={() => setShowCustomTitle(!showCustomTitle)}
                    className="px-3 py-1.5 text-sm bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-700 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                    title="自定义视频名称"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
                    </svg>
                  </button>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() => setShowApiSelector(!showApiSelector)}
                      className="px-3 py-1.5 text-sm bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-700 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors flex items-center gap-1"
                    >
                      <span>{PARSE_APIS[currentApiIndex].name}</span>
                      <svg 
                        xmlns="http://www.w3.org/2000/svg" 
                        fill="none" 
                        viewBox="0 0 24 24" 
                        strokeWidth={1.5} 
                        stroke="currentColor" 
                        className={`w-3 h-3 transition-transform ${showApiSelector ? 'rotate-180' : ''}`}
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
                      </svg>
                    </button>
                    
                    {showApiSelector && (
                      <div 
                        ref={apiSelectorRef}
                        className="absolute top-full right-0 mt-1 w-40 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-sm z-10"
                      >
                        <ul className="py-1">
                          {PARSE_APIS.map((api, index) => (
                            <li key={index}>
                              <button
                                type="button"
                                onClick={() => selectApi(index)}
                                disabled={!api.available}
                                className={`w-full text-left px-3 py-2 text-sm flex justify-between items-center ${
                                  !api.available ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-50 dark:hover:bg-gray-700'
                                } ${
                                  index === currentApiIndex ? 'bg-gray-50 dark:bg-gray-700 font-medium' : ''
                                }`}
                              >
                                <span>{api.name}</span>
                                {api.tag && (
                                  <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100">
                                    {api.tag}
                                  </span>
                                )}
                              </button>
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </div>
                  <button
                    type="submit"
                    disabled={loading || !PARSE_APIS[currentApiIndex].available}
                    className="px-3 py-1.5 text-sm text-white bg-black dark:bg-white dark:text-black rounded-md hover:bg-gray-800 dark:hover:bg-gray-200 disabled:opacity-50"
                  >
                    {loading ? '解析中...' : '解析'}
                  </button>
                </div>
              </form>
              
              {showCustomTitle && (
                <div 
                  ref={customTitleRef}
                  className="mt-2 p-3 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-gray-900"
                >
                  <label className="block text-sm font-medium mb-1">
                    自定义视频名称:
                  </label>
                  <input
                    type="text"
                    value={customTitle}
                    onChange={(e) => setCustomTitle(e.target.value)}
                    placeholder="输入易于识别的视频名称"
                    className="w-full py-2 px-3 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-black focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500"
                    maxLength={50}
                  />
                  <button
                    type="button"
                    onClick={() => setShowDescription(!showDescription)}
                    className="mt-2 text-sm text-blue-500 dark:text-blue-400 flex items-center"
                  >
                    <span>{showDescription ? "隐藏简介" : "添加视频简介"}</span>
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="ml-1 w-4 h-4">
                      <path strokeLinecap="round" strokeLinejoin="round" d={showDescription ? "M4.5 15.75l7.5-7.5 7.5 7.5" : "M19.5 8.25l-7.5 7.5-7.5-7.5"} />
                    </svg>
                  </button>
                </div>
              )}
              
              {showDescription && (
                <div
                  ref={descriptionRef}
                  className="mt-2 p-3 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-gray-900"
                >
                  <label className="block text-sm font-medium mb-1">
                    视频简介:
                  </label>
                  <textarea
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="输入视频的简介描述"
                    className="w-full py-2 px-3 border border-gray-200 dark:border-gray-800 rounded-lg bg-white dark:bg-black focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500"
                    rows={3}
                    maxLength={200}
                  />
                  <div className="text-xs text-right text-gray-400 mt-1">
                    {description.length}/200
                  </div>
                </div>
              )}
              
              {error && (
                <div className="mt-3 text-sm text-red-500 dark:text-red-400">
                  {error}
                </div>
              )}
              
              <div className="mt-3 text-sm text-gray-500 dark:text-gray-400">
                支持爱奇艺、优酷、腾讯视频等主流视频平台
              </div>
              
              <div className="mt-2 text-sm flex items-center">
                <span className="text-gray-500 dark:text-gray-400 mr-2">播放方式: </span>
                <span className={`font-medium ${playInNewTab ? 'text-blue-500 dark:text-blue-400' : 'text-gray-700 dark:text-gray-300'}`}>
                  {playInNewTab ? '新标签页打开' : '内嵌播放'}
                </span>
                <span className="text-xs text-gray-400 ml-2">(可在设置中修改)</span>
              </div>
            </div>
          </section>
          
          {/* 内嵌视频播放区域 */}
          {isEmbedPlaying && (
            <section id="video-player-section" className="mb-12">
              <div className="relative">
                <div className="flex justify-between items-center mb-2">
                  <h2 className="text-xl font-medium truncate">{embedTitle || '正在播放'}</h2>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={openInNewTab}
                      className="text-gray-500 hover:text-blue-500 transition-colors"
                      aria-label="在新标签页打开"
                      title="在新标签页打开"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-5 h-5">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                      </svg>
                    </button>
                    <button
                      onClick={closeEmbedPlayer}
                      className="text-gray-500 hover:text-red-500 transition-colors"
                      aria-label="关闭播放器"
                      title="关闭播放器"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </div>
                </div>
                <div className="relative">
                  <ReactVideoPlayer 
                    url={currentPlayingUrl} 
                    title={embedTitle} 
                    onLoad={handleIframeLoad}
                    onError={handleIframeError}
                    isLoading={iframeLoading}
                    hasError={iframeError}
                    hasTimeout={loadingTimeout}
                    onOpenInNewTab={openInNewTab}
                  />
                </div>
              </div>
            </section>
          )}
        </main>

        {/* 页脚 */}
        <footer className="border-t border-gray-100 dark:border-gray-800 py-6 mt-auto">
          <div className="max-w-5xl mx-auto px-4 text-center">
            <p className="text-sm text-gray-500 dark:text-gray-400">本工具仅用于学习和研究，请勿用于非法用途</p>
          </div>
        </footer>
      </div>
    </div>
  );
}
